package zy.vo.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zy.entity.base.type.T_Base_Type;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TypeVO {
	public static Map<String, String> Convert(List<T_Base_Type> list,List<Object> rootCtCode){
		Map<String, String> resultMap = new HashMap<String, String>();
		if(list == null || list.isEmpty()){
			return resultMap;
		}
		if (rootCtCode == null || rootCtCode.isEmpty()) {
			return resultMap;
		}
		String jsonStr  = "";
		for (int i = 0; i < rootCtCode.size(); i++) {
			jsonStr = piTypeToTree(list, rootCtCode.get(i).toString());
			if (jsonStr != null && !"".equals(jsonStr)) {
				JSONArray jsonArray=JSONArray.parseArray(jsonStr);
				for (int index = 0; index < jsonArray.size(); index++) {
					JSONObject jsonObject = jsonArray.getJSONObject(index);
					resultMap.put(jsonObject.getString("id"), rootCtCode.get(i).toString());
				}
			}
		}
		return resultMap;
	}
	public static String piTypeToTree(List<T_Base_Type> list,String rootCode){
		String treeHtml = "";
		if(list != null && list.size() >0){
			treeHtml = (initTree(list,rootCode));
			if(treeHtml != null && !"".equals(treeHtml)){
				treeHtml = (treeHtml.toString().substring(0, treeHtml.lastIndexOf(",")));
				treeHtml = "["+treeHtml+"]";
			}
		}
		return treeHtml;
	}
	public static String initTree(List<T_Base_Type> list, String rootCode){
		StringBuffer json = new StringBuffer(""); 
		List<T_Base_Type> nodeList = isHasChild(list, rootCode); // 获得集合中的父节点下的子集list  mn_IsHaveChildMenuItem
		list.remove(nodeList);
		// 循环子集
		//json.append("{");
		for (T_Base_Type node : nodeList) {
			List<T_Base_Type> Nodes = isHasChild(list, node.getTp_code());
			json.append("{id:'" + node.getTp_code() + "',pId:'"+node.getTp_upcode()+"',name:'"+node.getTp_name()+"'");
			if (Nodes.size() > 0) {
				json.append(",open:false");
			}
			json.append("},");
			// 查询全部集合下，是否存在该子集OID的子子集
			if (Nodes.size() > 0) {
				json.append(initTree(list, node.getTp_code())); // 递归树，传入子子集，子集父节点
			}
		}
		return json.toString();
	}
	public static List<T_Base_Type> isHasChild(List<T_Base_Type> list, String Parent) {
		  List<T_Base_Type> nodeList = new ArrayList<T_Base_Type>();
		  for (T_Base_Type comm : list) {
		   // 如果数据的父节点==Parent的值，则该数据为子节点，存入list<SysRole>
			   if (comm.getTp_upcode().equals(Parent)) {
				   nodeList.add(comm);
			   }
		  }
		  return nodeList;
	 }
}
